<?php
namespace app\h5api\controller;

use app\common\model\GoodsRecord;
use app\common\model\GrowthLog;
use app\common\model\Reserveorder;
use app\common\model\Shops;
use app\common\model\User;
use app\h5api\validate\Reserve;
use think\facade\Config;

class Place extends Base
{
    /**
     * @route('h5/GoToPlace')
     * 购物车下单
     */
    public function GoToPlace()
    {
        $ids = input('post.cart_ids');
        $receive_id = input('post.receive_id');
        $address_id = input('post.address_id');
        $pay_end = input('post.pay_end',1);
        $CartModel = new \app\common\model\Cart();
        $AddressModel = new \app\common\model\Address();
        $OrderModel = new \app\common\model\Order();
        $user = $this->GetUserInfo();
//        var_dump($user);die;
        $address = $AddressModel->checkaddress($user['user_id'],$address_id);
		if(!$address){
            $this->result([],-1,'用户不存在的收货地址');
        }
		$data = $CartModel->Settlement($user,$ids,$receive_id);
//		var_dump($data);die;
		if(!$data){
			$this->result([],-1,$CartModel->getError());
//			$this->result([],-1,'商铺或者商品已下架');
		}
//		var_dump($data['price']['pay_amount']);die;
        $createorders = $OrderModel->placecreateorder($user,$ids,$data['products'],$data['price'],$address,$receive_id);
//		var_dump($createorders);die;
		if($createorders['code'] === false){
		    $this->result([],-1,$OrderModel->getError());
        }
//		var_dump($createorders);
        if($pay_end == 1){
            $wxconfig = Config::pull('weixin');
        } else {
            $wxconfig = Config::pull('weixin_applet');
        }
//		var_dump($wxconfig);die;
        $notify = "/h5/notify";
        $rs = $OrderModel->wxpay($user,$createorders['data']['paymentsid'],$wxconfig,$notify,$pay_end);
        if($rs === false){
            $this->result([],-1,$OrderModel->getError());
        }
        $rs['data']['payments_id'] = $createorders['data']['paymentsid'];
        $rs['data']['order_id'] = $createorders['data']['orders'][0];
//        $rs['data']['order_ids'] = $createorders['data']['orders'];
        $rs['data']['is_pay'] = false;
		$this->result($rs,1,'操作成功');
    }


    /**
     * @route('h5/UncommonPlace')
     * 非购物车下单
     */
    public function UncommonPlace()
    {
        $product_id = input('post.product_id');
        $stock_id = input('post.stock_id');
        $quantity = input('post.quantity');
        $receive_id = input('post.receive_id');
        $address_id = input('post.address_id');
        $pay_end = input('post.pay_end',1);
        $AddressModel = new \app\common\model\Address();
        $OrderModel = new \app\common\model\Order();
        $quantity = empty($quantity)?"1":$quantity;
        $user = $this->GetUserInfo();
//        var_dump($user);die;
        $data = $OrderModel->checkplace($user,$product_id,$stock_id,$quantity,$receive_id);
        if($data === false){
            $this->result([],-1,$OrderModel->getError());
        }
//        var_dump($data['productinfo']['class_id']);die;
        $orderid = 0;
        switch($data['productinfo']['class_id']){
            case 4: // 团餐
//                echo 1;
                $reserve_info = [
                    'persons' => input('post.persons'),
                    'place_time' => input('post.place_time'),
                    'sex' => input('post.sex'),
                    'reserve_uname' => input('post.reserve_uname'),
                    'remark' => input('post.remark'),
                    'shop_id' => input('post.shop_id'),
                    'reserve_uphone' => input('post.reserve_uphone'),
                ];
                $rs = $OrderModel->placeteamorder($user,$data,$quantity,$reserve_info,$receive_id);
                if($rs['code'] === false){
                    $this->result([],-1,$OrderModel->getError());
                }
                $orderid = $rs['data']['orderid'];
                $userModel = new User();
                $userModel->UpdateUserMessgeCount($user['user_id'],1,'booking');
                break;
            case 3: // 爱心餐
//                echo 2;
                $rs = $OrderModel->placeloveorder($user,$data,$quantity);
                if($rs['code'] === false){
                    $this->result([],-1,$OrderModel->getError());
                }
                $rs['data']['is_pay'] = true;
                $goodsModel = new GoodsRecord();
                $record = $goodsModel->getOne([['order_id','=',$rs['data']['orderid']]],'access_code');
                $rs['data']['order_id'] = $rs['data']['orderid'];
                $rs['data']['access_code'] = $record['access_code'];
                $this->result($rs,1,'操作成功');
                break;
            case 2: // 兑换商品
//                echo 3;
                $address = $AddressModel->checkaddress($user['user_id'],$address_id);
                if(!$address){
                    $this->result([],-1,'用户不存在的收货地址');
                }
                $rs = $OrderModel->placeexchangeorder($user,$data,$quantity,$address);
                if($rs['code'] === false){
                    $this->result([],-1,$OrderModel->getError());
                }
                $rs['data']['order_id'] = $rs['data']['orderid'];
                if($rs['data']['paymentsid'] == 0){
                    $growthModel = new GrowthLog();
                    $growthModel->exchangerecord($rs['data']['orderid'],$user);
                    $rs['data']['is_pay'] = true;
                    $this->result($rs,1,'操作成功');
                }
                break;
            default:
                $this->result([],-1,"该类型商品无法下单");
                break;
        }
//        die;
//		var_dump($createorders);die;
        if($pay_end == 1){
            $wxconfig = Config::pull('weixin');
        } else {
            $wxconfig = Config::pull('weixin_applet');
        }
        $notify = "/h5/notify";
        $rs = $OrderModel->wxpay($user,$rs['data']['paymentsid'],$wxconfig,$notify,$pay_end);
        if($rs === false){
            $this->result([],-1,$OrderModel->getError());
        }
        $orderid !== 0?$rs['data']['order_id'] = $orderid:'';
        $rs['data']['is_pay'] = false;
		$this->result($rs,1,'操作成功');
    }

    /**
     * @route('h5/ToBePaid')
     * 订单待支付去支付
     */
    public function ToBePaid()
    {
        $orderModel = new \app\common\model\Order();
        $user = $this->GetUserInfo();
        $pay_end = input('post.pay_end',1);
//        var_dump($user);die;
        $where = [
            'user_id' => $user['user_id'],
            'order_id' => input('post.order_id'),
        ];
        $thecancel = $orderModel->tobepaidordercheck($where);
        if($thecancel === false){
            $this->result([],-1,$orderModel->getError());
        }
//        var_dump($thecancel);die;
        $result['data']['is_can_pay'] = false;
        switch($thecancel['code']){
            case 2:
                $rs = $orderModel->updateorderandstock($thecancel['data']['details'],$thecancel['data']['order']);
                if($rs === false){
                    $this->result($result,-1,$orderModel->getError());
                }
                $this->result($result,1,$thecancel['msg']."已取消订单");
                break;
            case 1:
                if($pay_end == 1){
                    $wxconfig = Config::pull('weixin');
                } else {
                    $wxconfig = Config::pull('weixin_applet');
                }
//                var_dump($wxconfig);die;
                $notify = "/h5/notify";
                $rs = $orderModel->wxpay($user,$thecancel['data']['order']['payments_id'],$wxconfig,$notify,$pay_end);
                if($rs === false){
                    $this->result($result,-1,$orderModel->getError());
                }
                $result['data'] = $rs;
                $result['data']['payments_id'] = $thecancel['data']['order']['payments_id'];
                $result['data']['order_id'] = $thecancel['data']['order']['order_id'];
                $result['data']['is_can_pay'] = true;
                $this->result($result,1,'操作成功');
                break;
            default:
                $this->result($result,-1,$thecancel['msg']);
                break;
        }
    }

    /**
     * @route('h5/GoToReserve','post')
     * 订座下单
     */
    public function GoToReserve()
    {
        $param = input('post.');
        $pay_end = input('post.pay_end',1);
        $validate = new Reserve();
        $checkres = $validate->scene("checkReserve")->check($param);
        if (!$checkres) {
            $this->result([],-1,$validate->getError());
        }
        $shopModel = new Shops();
        $shop = $shopModel->getOneShop($param['shop_id'],'*');
        if(empty($shop)){
            $this->result([],-1,'不存在该店铺');
        }
        if(empty($shop['reserve_info']) || $shop['is_business'] == 2){
            $this->result([],-1,'店铺暂不提供订座');
        }
        $reserve_info = json_decode($shop['reserve_info'],true);
        $orderModel = new Reserveorder();
        $where = [
            ['place_time','=',date('Y-m-d H:i',strtotime($param['place_time']))],
            ['shop_id','=',$param['shop_id']],
            ['order_status','=',2],
        ];
        $count = $orderModel
            ->where($where)
            ->count();
        if($count + 1 > $reserve_info['limit_number']){
            $this->result([],-1,'已达该时间段预约单数上限');
        }
        $user = $this->GetUserInfo();
        $orderModel = new Reserveorder();
        $data['payinfo']['allcoupon_amount'] = 0;
        $data['payinfo']['allorder_amount'] = 0;
        $data['payinfo']['pay_amount'] = 0;
//        var_dump($data);die;
        $param['place_time'] = strtotime($param['place_time']);
        $rs = $orderModel->placereserveorder($user,$shop,$data,$param);
        if($rs['code'] === false){
            $this->result([],-1,$orderModel->getError());
        }
        $rs['data']['is_pay'] = true;
        if($rs['data']['paymentsid'] != 0){
            if($pay_end == 1){
                $wxconfig = Config::pull('weixin');
            } else {
                $wxconfig = Config::pull('weixin_applet');
            }
            $notify = "/h5/notify";
            $rs = $orderModel->wxpay($user,$rs['data']['paymentsid'],$wxconfig,$notify,$pay_end);
            if($rs === false){
                $this->result([],-1,$orderModel->getError());
            }
            $rs['data']['is_pay'] = false;
        }

        $this->result($rs,1,'操作成功');
    }
}
